package com.yc.navy.springmvc.controller;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.yc.navy.springmvc.bean.MemberInfo;
import com.yc.navy.springmvc.enums.ResultEnum;
import com.yc.navy.springmvc.service.IMemberInfoService;
import com.yc.navy.springmvc.util.ConstantIfo;
import com.yc.navy.springmvc.vo.ResultVO;

@RestController
@RequestMapping("/menber")
public class MemberInfoController {
	@Autowired
	private IMemberInfoService memberInfoService;
	
	/**
	 * 发送邮箱验证码
	 * @return
	 */
	@PostMapping("/code")
	public ResultVO SendCode(HttpSession session, HttpServletResponse response) {
		response.setHeader("paragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		
		//String code = getRandomCode();
		return null;
		
	}
	/**
	 * 注册
	 * @param mf
	 * @return
	 */
	@PostMapping("/reg")
	public ResultVO reg(MemberInfo mf) {
		int result = memberInfoService.reg(mf);
		if(result == -100) {
			return new ResultVO(ResultEnum.CHECK_ERROR);
		}
		if(result > 0) {
			return new ResultVO(ResultEnum.SUCCESS);
		}
		return new ResultVO(ResultEnum.ERROP);
	}
	
	/**
	 * 登录
	 */
	@PostMapping("/login")
	public ResultVO login(MemberInfo mf, String code, HttpSession session) {
		Object obj = session.getAttribute(ConstantIfo.LOGINCODE);
		if(obj == null) {
			return new ResultVO(ResultEnum.CODE_TIMEOUT);
		}
		
		if(!code.equalsIgnoreCase(code)) {
			return new ResultVO(ResultEnum.CODE_ERROR);//验证码错误
		}
		
		MemberInfo member = memberInfoService.login(mf);
		if(member == null) {
			return new ResultVO(ResultEnum.ERROP);//校验错误
		}
		
		session.setAttribute(ConstantIfo.CURRENTLOGINMEMBER, member);
		return new ResultVO(ResultEnum.SUCCESS);
	}
	
	/**
	 * 获取当前登录的用户信息
	 */
	@GetMapping("/info")
	public ResultVO getInfo(HttpSession session) {
		Object obj = session.getAttribute(ConstantIfo.CURRENTLOGINMEMBER);
		if(obj == null) {
			return new ResultVO(ResultEnum.LOGIN_ERROR);
		}
		return new ResultVO(ResultEnum.SUCCESS, obj);	
	}
	
	protected static Integer getMno(HttpSession session) {
		Object member = session.getAttribute(ConstantIfo.CURRENTLOGINMEMBER);
		if( member == null ) {
			return null;
		}
		MemberInfo mf = (MemberInfo) member;
		return mf.getMno();
	}
}
